package com.wuzihao.reggie.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuzihao.reggie.common.BaseContext;
import com.wuzihao.reggie.common.CustomException;
import com.wuzihao.reggie.entity.*;
import com.wuzihao.reggie.mapper.OrderMapper;
import com.wuzihao.reggie.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    ShoppingCartService shoppingCartService;

    @Autowired
    UserService userService;

    @Autowired
    AddressBookService addressBookService;

    @Autowired
    OrderService orderService;

    @Autowired
    OrderDetailService orderDetailService;

    @Override
    public void submit(Orders orders) {
        //1.获得当前用户id
        Long currentId = BaseContext.getCurrentId();

        //2.获得当前购物车数据
        List<ShoppingCart> cartList = shoppingCartService.list(new QueryWrapper<ShoppingCart>().eq("user_id", currentId));
        if(cartList == null && cartList.size() == 0){
            throw new CustomException("当前购物车为空，无法结算");
        }

        //3.获得用户信息
        User user = userService.getById(currentId);

        //4.获得当前地址信息
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBookEntity = addressBookService.getById(addressBookId);
        if (addressBookEntity == null){
            throw new CustomException("当前用户地址信息有误，无法下单");
        }

        long orderId = IdWorker.getId();//订单号

        AtomicInteger amount = new AtomicInteger(0);

        //封装属性
        List<OrderDetail> orderDetails = cartList.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(currentId);
        orders.setNumber(String.valueOf(orderId));
        orders.setUserName(user.getName());
        orders.setConsignee(addressBookEntity.getConsignee());
        orders.setPhone(addressBookEntity.getPhone());
        orders.setAddress((addressBookEntity.getProvinceName() == null ? "" : addressBookEntity.getProvinceName())
                + (addressBookEntity.getCityName() == null ? "" : addressBookEntity.getCityName())
                + (addressBookEntity.getDistrictName() == null ? "" : addressBookEntity.getDistrictName())
                + (addressBookEntity.getDetail() == null ? "" : addressBookEntity.getDetail()));

        //5.向orders表中插入一条数据
        orderService.save(orders);

        //6.向orderDetail表中插入多条数据
        orderDetailService.saveBatch(orderDetails);

        //6.清空购物车
        shoppingCartService.remove(new QueryWrapper<ShoppingCart>().eq("user_id", currentId));
    }
}
